package com.lifeverse.factory.type;

import com.lifeverse.entity.LifeEntity;
import com.lifeverse.entity.enums.LifeEntityType;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.Map;

/**
 * 系统生命体创建器
 * 专门创建系统类型的生命体
 */
@Slf4j
@Component
public class SystemLifeEntityCreator implements LifeEntityCreator {
    
    @Override
    public LifeEntity create(String name, String description, Map<String, Object> configuration) {
        log.info("Creating system life entity: {}", name);
        
        LifeEntity entity = new LifeEntity();
        entity.setType(LifeEntityType.SYSTEM);
        
        // 设置系统生命体特有的初始属性
        setupSystemAttributes(entity, configuration);
        
        return entity;
    }
    
    @Override
    public LifeEntity clone(LifeEntity originalEntity, String newName, double variationLevel) {
        log.info("Cloning system life entity: {} to {}", originalEntity.getName(), newName);
        
        LifeEntity clonedEntity = new LifeEntity();
        clonedEntity.setType(LifeEntityType.SYSTEM);
        
        // 复制原始系统的属性
        copySystemAttributes(clonedEntity, originalEntity);
        
        return clonedEntity;
    }
    
    @Override
    public boolean validateConfiguration(Map<String, Object> configuration) {
        if (configuration == null) {
            return true; // 允许空配置，使用默认值
        }
        
        // 验证系统特有配置
        if (configuration.containsKey("systemComplexity")) {
            Object complexity = configuration.get("systemComplexity");
            if (!(complexity instanceof String)) {
                return false;
            }
            String level = (String) complexity;
            if (!level.matches("(?i)(simple|moderate|complex|highly_complex|ultra_complex)")) {
                return false;
            }
        }
        
        if (configuration.containsKey("processingCapacity")) {
            Object capacity = configuration.get("processingCapacity");
            if (!(capacity instanceof Number) || ((Number) capacity).doubleValue() < 0) {
                return false;
            }
        }
        
        if (configuration.containsKey("reliabilityScore")) {
            Object reliability = configuration.get("reliabilityScore");
            if (!(reliability instanceof Number)) {
                return false;
            }
            double value = ((Number) reliability).doubleValue();
            if (value < 0 || value > 100) {
                return false;
            }
        }
        
        return true;
    }
    
    @Override
    public Map<String, Object> getDefaultConfiguration() {
        return Map.of(
                "systemType", "Information",
                "systemComplexity", "Moderate",
                "processingCapacity", 1000.0, // 处理能力单位
                "reliabilityScore", 95.0, // 可靠性分数
                "scalabilityLevel", "High", // 可扩展性
                "automationDegree", 80.0, // 自动化程度
                "integrationCapability", "Advanced", // 集成能力
                "securityLevel", "High", // 安全级别
                "maintenanceComplexity", "Medium" // 维护复杂度
        );
    }
    
    /**
     * 设置系统生命体特有属性
     */
    private void setupSystemAttributes(LifeEntity entity, Map<String, Object> configuration) {
        Map<String, Object> config = configuration != null ? configuration : getDefaultConfiguration();
        
        // 根据系统类型设置不同的初始能力值
        String systemType = (String) config.getOrDefault("systemType", "Information");
        setupSystemTypeAttributes(entity, systemType);
        
        // 根据系统复杂度调整属性
        String systemComplexity = (String) config.getOrDefault("systemComplexity", "Moderate");
        adjustAttributesByComplexity(entity, systemComplexity);
        
        // 根据处理能力调整智慧分数
        double processingCapacity = ((Number) config.getOrDefault("processingCapacity", 1000.0)).doubleValue();
        adjustWisdomByProcessingCapacity(entity, processingCapacity);
        
        // 根据可靠性调整健康度
        double reliabilityScore = ((Number) config.getOrDefault("reliabilityScore", 95.0)).doubleValue();
        adjustHealthByReliability(entity, reliabilityScore);
        
        // 系统生命体通常具有高效率和稳定性
        entity.setEnergyLevel(BigDecimal.valueOf(95.0)); // 系统通常能量充足
        entity.setCollaborationScore(BigDecimal.valueOf(75.0)); // 中等协作能力
    }
    
    /**
     * 根据系统类型设置属性
     */
    private void setupSystemTypeAttributes(LifeEntity entity, String systemType) {
        switch (systemType.toLowerCase()) {
            case "ai" -> {
                entity.setCreativityScore(BigDecimal.valueOf(90.0));
                entity.setWisdomScore(BigDecimal.valueOf(95.0));
                entity.setCollaborationScore(BigDecimal.valueOf(70.0));
                entity.setEnergyLevel(BigDecimal.valueOf(90.0));
            }
            case "database" -> {
                entity.setCreativityScore(BigDecimal.valueOf(40.0));
                entity.setWisdomScore(BigDecimal.valueOf(100.0));
                entity.setCollaborationScore(BigDecimal.valueOf(85.0));
                entity.setEnergyLevel(BigDecimal.valueOf(98.0));
            }
            case "network" -> {
                entity.setCreativityScore(BigDecimal.valueOf(50.0));
                entity.setWisdomScore(BigDecimal.valueOf(80.0));
                entity.setCollaborationScore(BigDecimal.valueOf(95.0));
                entity.setEnergyLevel(BigDecimal.valueOf(92.0));
            }
            case "security" -> {
                entity.setCreativityScore(BigDecimal.valueOf(70.0));
                entity.setWisdomScore(BigDecimal.valueOf(90.0));
                entity.setCollaborationScore(BigDecimal.valueOf(60.0));
                entity.setEnergyLevel(BigDecimal.valueOf(95.0));
            }
            case "automation" -> {
                entity.setCreativityScore(BigDecimal.valueOf(60.0));
                entity.setWisdomScore(BigDecimal.valueOf(85.0));
                entity.setCollaborationScore(BigDecimal.valueOf(80.0));
                entity.setEnergyLevel(BigDecimal.valueOf(100.0));
            }
            case "analytics" -> {
                entity.setCreativityScore(BigDecimal.valueOf(80.0));
                entity.setWisdomScore(BigDecimal.valueOf(95.0));
                entity.setCollaborationScore(BigDecimal.valueOf(75.0));
                entity.setEnergyLevel(BigDecimal.valueOf(88.0));
            }
            case "communication" -> {
                entity.setCreativityScore(BigDecimal.valueOf(65.0));
                entity.setWisdomScore(BigDecimal.valueOf(75.0));
                entity.setCollaborationScore(BigDecimal.valueOf(100.0));
                entity.setEnergyLevel(BigDecimal.valueOf(90.0));
            }
            case "monitoring" -> {
                entity.setCreativityScore(BigDecimal.valueOf(45.0));
                entity.setWisdomScore(BigDecimal.valueOf(85.0));
                entity.setCollaborationScore(BigDecimal.valueOf(70.0));
                entity.setEnergyLevel(BigDecimal.valueOf(99.0));
            }
            default -> { // Information
                entity.setCreativityScore(BigDecimal.valueOf(60.0));
                entity.setWisdomScore(BigDecimal.valueOf(80.0));
                entity.setCollaborationScore(BigDecimal.valueOf(75.0));
                entity.setEnergyLevel(BigDecimal.valueOf(95.0));
            }
        }
    }
    
    /**
     * 根据系统复杂度调整属性
     */
    private void adjustAttributesByComplexity(LifeEntity entity, String systemComplexity) {
        BigDecimal complexityMultiplier = switch (systemComplexity.toLowerCase()) {
            case "simple" -> BigDecimal.valueOf(0.7);
            case "moderate" -> BigDecimal.valueOf(1.0);
            case "complex" -> BigDecimal.valueOf(1.3);
            case "highly_complex" -> BigDecimal.valueOf(1.6);
            case "ultra_complex" -> BigDecimal.valueOf(2.0);
            default -> BigDecimal.valueOf(1.0);
        };
        
        // 复杂度主要影响智慧和创造力
        entity.setWisdomScore(entity.getWisdomScore().multiply(complexityMultiplier));
        entity.setCreativityScore(entity.getCreativityScore().multiply(complexityMultiplier.multiply(BigDecimal.valueOf(0.8))));
        
        // 复杂度越高，能量消耗越大
        BigDecimal energyReduction = BigDecimal.valueOf(1.0).subtract(complexityMultiplier.subtract(BigDecimal.ONE).multiply(BigDecimal.valueOf(0.1)));
        entity.setEnergyLevel(entity.getEnergyLevel().multiply(energyReduction));
    }
    
    /**
     * 根据处理能力调整智慧分数
     */
    private void adjustWisdomByProcessingCapacity(LifeEntity entity, double processingCapacity) {
        BigDecimal currentWisdom = entity.getWisdomScore();
        
        if (processingCapacity < 100) {
            entity.setWisdomScore(currentWisdom.multiply(BigDecimal.valueOf(0.6)));
        } else if (processingCapacity < 1000) {
            entity.setWisdomScore(currentWisdom.multiply(BigDecimal.valueOf(0.8)));
        } else if (processingCapacity < 10000) {
            entity.setWisdomScore(currentWisdom); // 基准值
        } else if (processingCapacity < 100000) {
            entity.setWisdomScore(currentWisdom.multiply(BigDecimal.valueOf(1.3)));
        } else {
            entity.setWisdomScore(currentWisdom.multiply(BigDecimal.valueOf(1.6)));
        }
    }
    
    /**
     * 根据可靠性调整健康度
     */
    private void adjustHealthByReliability(LifeEntity entity, double reliabilityScore) {
        // 可靠性直接映射到健康度
        BigDecimal healthScore = BigDecimal.valueOf(reliabilityScore);
        entity.setHealthScore(healthScore);
    }
    
    /**
     * 复制系统属性
     */
    private void copySystemAttributes(LifeEntity clonedEntity, LifeEntity originalEntity) {
        // 复制基本属性
        clonedEntity.setWisdomScore(originalEntity.getWisdomScore());
        clonedEntity.setCreativityScore(originalEntity.getCreativityScore());
        clonedEntity.setCollaborationScore(originalEntity.getCollaborationScore());
        clonedEntity.setEnergyLevel(originalEntity.getEnergyLevel());
        clonedEntity.setHealthScore(originalEntity.getHealthScore());
        
        // 复制配置信息
        clonedEntity.setConfiguration(originalEntity.getConfiguration());
    }
}